/*
copia le sistemazioni presenti su un contratto e assenti su altri 
*/
--SELECT * INTO ALLOTMENT_DETT_OLD FROM ALLOTMENT_DETT
DECLARE @NUMCONTR INT, @CODICERIF_ALLOTMENT VARCHAR(30)
DECLARE CURSORE CURSOR FOR SELECT DISTINCT CODICERIF_ALLOTMENT, NUMCONTR FROM ALLOTMENT_DETT WHERE NUMCONTR BETWEEN 2 AND 223 ORDER BY NUMCONTR
OPEN CURSORE
FETCH NEXT FROM CURSORE INTO @CODICERIF_ALLOTMENT, @NUMCONTR
WHILE @@FETCH_STATUS >=0
BEGIN
BEGIN TRANSACTION
	INSERT INTO ALLOTMENT_DETT (CODICERIF_ALLOTMENT, CATKEY, INIZIALE, VENDUTO, DISPONIBILE, LUNGHEZZA, QTA, ALTEZZA, NUMCONTR)
	SELECT @CODICERIF_ALLOTMENT, CATKEY, INIZIALE, VENDUTO, DISPONIBILE, LUNGHEZZA, QTA, ALTEZZA, @NUMCONTR
		FROM ALLOTMENT_DETT 
		WHERE CATKEY NOT IN (SELECT CATKEY FROM ALLOTMENT_DETT WHERE NUMCONTR=@NUMCONTR) AND NUMCONTR=1
	IF @@ERROR<>0
	BEGIN
		ROLLBACK TRANSACTION
		PRINT @NUMCONTR +' ERROR'
	END
	COMMIT TRANSACTION
FETCH NEXT FROM CURSORE INTO @CODICERIF_ALLOTMENT, @NUMCONTR	
END
CLOSE CURSORE
DEALLOCATE CURSORE
/*
SELECT * FROM ALLOTMENT_DETT 
		WHERE CATKEY NOT IN (SELECT CATKEY FROM ALLOTMENT_DETT WHERE NUMCONTR=223) AND NUMCONTR=1
*/

--aggiorno le corse
DECLARE @id_linea char(14), @cod_cfg_linea char(10)
DECLARE curs_corse SCROLL CURSOR FOR SELECT distinct id_linea, cod_cfg_linea
                               FROM corse  where codtratta in ('ANSP', 'SPAN')


DECLARE @esito2 bit, @catkey int
DECLARE curs_allotment SCROLL CURSOR FOR SELECT a.numcontr, catkey 
                                      FROM allotment a INNER JOIN allotment_dett ad ON a.numcontr = ad.numcontr WHERE
                                     id_linea = @id_linea and cod_cfg_linea = @cod_cfg_linea and ad.numcontr between 2 and 223
OPEN curs_allotment
FETCH NEXT FROM curs_allotment INTO @numcontr, @catkey
WHILE @@FETCH_STATUS = 0
   BEGIN
   EXEC GG_SitAggiornaFromAllotment  @numcontr, @catkey, 1,@esito2 output, 0.0
   IF (@@ERROR <> 0)
       BEGIN
		GOTO ON_ERROR
       END
   FETCH NEXT FROM curs_allotment INTO @numcontr, @catkey
   END
CLOSE curs_allotment
DEALLOCATE curs_allotment